<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：模块公共文件。
 *
 **/


function UpImage($callBack = "image", $width = 100, $height = 100, $image = "")
{

    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
         <input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage($callBack = "image", $width = 100, $height = 100, $image = "")
{
    
    echo '<iframe scrolling="no" frameborder="0" border="0"  width=' . $width . ' height="' . $height . '" src="' . U('Upload/batchpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
		<input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}


function UpImageCrop($callBack = "image", $width = 100, $height = 100, $image = "")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadcroppic',
        array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
         <input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}

/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
*/
function setting($k = 'all')
{
    $cache = S($k);
    //如果缓存不为空直接返回
    if (null != $cache) {
        return $cache;
    }
    $data = '';
    $setting = M('setting');
    //判断是否查询全部设置项
    if ($k == 'all') {
        $setting = $setting->field('k,v')->select();
        foreach ($setting as $v) {
            $config[$v['k']] = $v['v'];
        }
        $data = $config;

    } else {
        $result = $setting->where("k='{$k}'")->find();
        $data = $result['v'];

    }
    //建立缓存
    if ($data) {
        S($k, $data);
    }
    return $data;
}

/**
 * 函数：格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    /*
    *后续整强有力的加密函数
    */
    return md5('Q' . $password . 'W');

}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
        'smllletter' => 'abcdefghijklmnopqrstuvwxyz1234567890'
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//获取所有的子级id
function category_get_sons($sid, &$array = array())
{
    //获取当前sid下的所有子栏目的id
    $categorys = M("category")->where("pid = {$sid}")->select();

    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        category_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;

}

//获取地区所有的子级id
function area_get_sons($sid, &$array = array())
{
    //获取当前sid下的所有子栏目的id
    $categorys = M("area")->where("pid = {$sid}")->select();
    
    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        area_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;
    
}


/**
 * 获取文章url地址
 * url结构：ttp://wwww.Admin.com/分类/子分类/子分类/id.html
 * 使用方法：模板中{:articleUrl(array('aid'=>$val['aid']))}
 *
 *
 * @param $data
 * @return $string
 */
function articleUrl($data)
{
    //如果数组为空直接返回空字符
    if (!$data) {
        return '';
    }
    //如果参数错误直接返回空字符
    if (!isset($data['aid'])) {
        return '';
    }

    $aid = (int)$data['aid'];

    //获取文章信息
    $article = M('article')->where(array('aid' => $aid))->find();
    //获取当前内容所在分类
    $category = M('category')->where(array('id' => $article['sid']))->find();
    //获取当前分类
    $categoryUrl = $category['dir'];
    //遍历获取当前文章所在分类的有上级分类并且组合url
    while ($category['pid'] <> 0) {
        $category = M('category')->where(array('id' => $category['pid']))->find();
        $categoryUrl = $category['dir'] . "/" . $categoryUrl;
        //如果上级分类已经无上级分类则退出
    }

    $categoryUrl = __ROOT__ . "/" . $categoryUrl;
    //组合文章url
    $articleUrl = $categoryUrl . '/' . $aid . ".html";
    return $articleUrl;

}


/**
 * 截取字符串长度
 *
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    $str = htmlspecialchars_decode($str);
    $str = strip_tags($str);
    if(function_exists("mb_substr")){
        if($suffix)
            return mb_substr($str, $start, $length, $charset)."...";
            else
            {
                if(utf8_strlen($str)>$length)
                    
                    return mb_substr($str, $start, $length, $charset);
                    else
                        return mb_substr($str, $start, $length, $charset);
            }
            
    }
    elseif(function_exists('iconv_substr')) {
        if($suffix)
            return iconv_substr($str,$start,$length,$charset)."...";
            else
            {
                if(utf8_strlen($str)>$length)
                    return mb_substr($str, $start, $length, $charset);
                    else
                        return mb_substr($str, $start, $length, $charset);
            }
    }
    $re['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef]
                  [x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
    $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
    $re['gbk']    = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
    $re['big5']   = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix)
        return $slice."…";
        else
        {
            if(utf8_strlen($str)>$length)
                return $slice;
                else
                    return $slice;
        }
        return $slice;
}

function utf8_strlen($string = null) {
    // 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
    // 返回单元个数
    return count($match[0]);
}

function makecode($qrcode_path,$content,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel,$url){
    /**     参数详情：
     *      $qrcode_path:logo地址
     *      $content:需要生成二维码的内容
     *      $matrixPointSize:二维码尺寸大小
     *      $matrixMarginSize:生成二维码的边距
     *      $errorCorrectionLevel:容错级别
     *      $url:生成的带logo的二维码地址
     * */
    ob_clean ();
    Vendor('phpqrcode.phpqrcode');
    $object = new \QRcode();
    $qrcode_path_new = './Public/home/qrcode/code'.'_'.date("Ymdhis").'.png';//定义生成二维码的路径及名称
    $object::png($content,$qrcode_path_new, $errorCorrectionLevel, $matrixPointSize, $matrixMarginSize);
    $QR = imagecreatefromstring(file_get_contents($qrcode_path_new));//imagecreatefromstring:创建一个图像资源从字符串中的图像流
    $logo = imagecreatefromstring(file_get_contents($qrcode_path));
    $QR_width = imagesx($QR);// 获取图像宽度函数
    $QR_height = imagesy($QR);//获取图像高度函数
    $logo_width = imagesx($logo);// 获取图像宽度函数
    $logo_height = imagesy($logo);//获取图像高度函数
    $logo_qr_width = $QR_width / 4;//logo的宽度
    $scale = $logo_width / $logo_qr_width;//计算比例
    $logo_qr_height = $logo_height / $scale;//计算logo高度
    $from_width = ($QR_width - $logo_qr_width) / 2;//规定logo的坐标位置
    imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
    /**     imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
     *      参数详情：
     *      $dst_image:目标图象连接资源。
     *      $src_image:源图象连接资源。
     *      $dst_x:目标 X 坐标点。
     *      $dst_y:目标 Y 坐标点。
     *      $src_x:源的 X 坐标点。
     *      $src_y:源的 Y 坐标点。
     *      $dst_w:目标宽度。
     *      $dst_h:目标高度。
     *      $src_w:源图象的宽度。
     *      $src_h:源图象的高度。
     * */
    Header("Content-type: image/png");
    //$url:定义生成带logo的二维码的地址及名称
    imagepng($QR,$url);
}
function makecode_no_pic($content,$qrcode_path_new,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel){
    ob_clean ();
    Vendor('phpqrcode.phpqrcode');
    $object = new \QRcode();
    $object::png($content,$qrcode_path_new, $errorCorrectionLevel, $matrixPointSize, $matrixMarginSize);
}


function delDirAndFile( $dirName ){
    if($handle=opendir($dirName)){
        while(false!==($item=readdir($handle))){
            if($item!="."&&$item!=".."){
                if(is_dir("$dirName/$item")){
                    $this->delDirAndFile("$dirName/$item");
                }else{
                    unlink("$dirName/$item");
                }
            }
        }
        closedir($handle);
        //rmdir($dirName);
    }
}
